﻿#include "qterminalwidget.h"
#include "ui_qterminalwidget.h"
#include <QDebug>
#undef print
#define print qDebug()

qTerminalWidget::qTerminalWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::qTerminalWidget)
{
    ui->setupUi(this);
    ui->display->setFocus();
    ui->scrollBar->setSingleStep(1);
    ui->scrollBar->setPageStep(3);
    ui->scrollBar->setValue(0);
    ui->scrollBar->setEnabled(false);
    connect(ui->scrollBar, &QScrollBar::sliderMoved, ui->display,&qTerminalDisplay::sliderMovedScrollBarPosition);
    connect(ui->scrollBar, &QScrollBar::valueChanged, ui->display,&qTerminalDisplay::valueChangedSlots);
    connect(ui->display,&qTerminalDisplay::setScrollValue,this,[=](int min,int max,int page,int value){
        
         ui->scrollBar->setRange(min,max-page);
         ui->scrollBar->setPageStep(page);
        if(ui->scrollBar->isEnabled()==false)
            ui->scrollBar->setEnabled(true);
        if(ui->scrollBar->value()!=value)
            ui->scrollBar->setValue(value-page);
    });
    connect(ui->display,&qTerminalDisplay::setScrollBarPos,this,[=](int value){
        int pos = ui->scrollBar->value();

         ui->scrollBar->setValue(pos+value);
    });
    connect(ui->display,&qTerminalDisplay::setScrollPageSignal,this,[=](int page){
        int value = ui->scrollBar->value();
         ui->scrollBar->setMaximum(ui->scrollBar->maximum()-page);
         ui->scrollBar->setPageStep(page);
         ui->scrollBar->setValue(value-page);
    });
}

qTerminalWidget::~qTerminalWidget()
{
    if(ssh)
        delete ssh;
    delete ui;
}

void qTerminalWidget::connectSsh(libsshParams *param)
{
    if(param==nullptr)
        return;
    ssh = new libsshUtils(nullptr,param);
    connect(ssh,&libsshUtils::receiveData,ui->display,&qTerminalDisplay::recvData);
    connect(ssh,&libsshUtils::sshConnectedSignal,ui->display,&qTerminalDisplay::resizeSlots);
    connect(ui->display,&qTerminalDisplay::sendDataByteArrarySlgnal,ssh,&libsshUtils::sendData);
    connect(ui->display,&qTerminalDisplay::resizeSignal,ssh,&libsshUtils::sshResizeWindowSlots);
    ssh->initializeFunction();
}

void qTerminalWidget::setFocusSlots()
{
    ui->display->setFocus();
}

